<script setup lang="ts">
import dayjs from 'dayjs'
import { useForm, useTable } from '@/hooks'
import { ReportApi } from '@/apis'
import { formatMoney } from '@/utils/common'
import type { TableInstanceColumns } from '@/components/ProTable/type'

const today = dayjs()
const { form, resetForm } = useForm({
  dateFrom: today.startOf('month').format('YYYY-MM-DD'),
  dateTo: today.endOf('month').format('YYYY-MM-DD'),
})

const {
  tableData,
  loading,
  search,
} = useTable(() => ReportApi.getFinStat(form))

const columns: TableInstanceColumns[] = [
  { title: '序号', dataIndex: 'index', width: 66, align: 'center', fixed: 'left', render: ({ rowIndex }) => rowIndex + 1, summaryCellStyle: () => {
    return { backgroundColor: 'rgb(var(--arcoblue-6))', color: '#fff' }
  } },
  { title: '名称', dataIndex: 'name', fixed: 'left', width: 100 },
  { title: '账号', dataIndex: 'account', width: 120 },
  { title: '订单笔数', dataIndex: 'orderCount', width: 120 },
  { title: '订单总额', dataIndex: 'orderPrice', slotName: 'orderPrice', width: 120 },
  { title: '退款笔数', dataIndex: 'refundCount', width: 120 },
  { title: '退款总额', dataIndex: 'refundPrice', slotName: 'refundPrice', width: 120 },
]

const tableSummary = ({ columns, data }) => {
  const countData = {
    orderCount: 0,
    orderPrice: 0,
    refundCount: 0,
    refundPrice: 0,
  }
  data.forEach((record) => {
    countData.orderCount += record.orderCount
    countData.orderPrice += record.orderPrice
    countData.refundCount += record.refundCount
    countData.refundPrice += record.refundPrice
  })

  return [{
    index: '合计',
    orderCount: countData.orderCount,
    orderPrice: formatMoney(countData.orderPrice),
    refundCount: countData.refundCount,
    refundPrice: formatMoney(countData.refundPrice),
  }]
}

watch(form, () => search())
onMounted(() => {
  search()
})
</script>

<template>
  <ProPage title="财务收支统计" :flex-table="false" :loading="loading">
    <ProTable
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="false"
      :summary="tableSummary"
      @refresh="search"
    >
      <template #toolbar-left>
        <a-space>
          <RangePicker v-model:from="form.dateFrom" v-model:to="form.dateTo" :time="false" />
        </a-space>
      </template>
      <!-- <template #toolbar-right>
        <a-button type="text" size="medium" @click="onExportExcel">
          <template #icon>
            <icon-download />
          </template>
          <span>导出</span>
        </a-button>
      </template> -->
      <template #orderPrice="{ record }">
        {{ formatMoney(record.orderPrice) }}
      </template>
      <template #refundPrice="{ record }">
        {{ formatMoney(record.refundPrice) }}
      </template>
      <template #summary-cell="{ column, record, rowIndex }">
        <div>
          {{ record[column.dataIndex] }}
        </div>
      </template>
    </ProTable>
  </ProPage>
</template>

<style lang="less" scoped>
</style>
